package model

import (
	"fmt"
	"mq-apiserver/pkg/constvar"
	"mq-apiserver/util"

	validator "gopkg.in/go-playground/validator.v9"
)

type MQUser struct {
	BaseModel
	Username string `json:"username" gorm:"column:username;not null" binding:"required" validate:"min=5,max=32"`
	Pw       string `json:"pw" gorm:"column:pw;not null" binding:"required" validate:"min=5,max=128"`
	Super    uint8  `json:"super" gorm:"column:super;not null" binding:"required" `
	State    uint8  `json:"state"`
}
type MQUserChangePw struct {
	BaseModel
	Username string `json:"username" gorm:"column:username;not null" binding:"required" validate:"min=1,max=32"`
	Pw       string `json:"pw" gorm:"column:pw;not null" binding:"required" validate:"min=5,max=128"`
}

type MQUserInfo struct {
	Id        uint64 `json:"id"`
	Username  string `json:"username"`
	Super     uint8  `json:"super"`
	State     uint8  `json:"state"`
	CreatedAt string `json:"createdAt"`
	UpdatedAt string `json:"updatedAt"`
}

// @ValidateMQUser 验证mq用户信息
func (u *MQUser) ValidateMQUser() error {
	validate := validator.New()
	return validate.Struct(u)
}

// @GetMQUser 使用 username 获取 mq 的用户信息
func GetMQUser(username string) (*ResUsername, error) {
	u := &ResUsername{}
	d := DB.Self.Table("users").Select("username").Where("username = ?", username).First(&u)
	return u, d.Error
}

// @EncryptMQUser 密码加密
func (u *MQUser) EncryptMQUser() (err error) {
	// 加密 密码
	u.Pw, err = util.PasswordEncode(u.Pw, "", 901)
	return
}

// @CreateMQUser 创建用户
func (u *MQUser) CreateMQUser() error {
	return DB.Self.Table("users").Create(&u).Error
}

// @DeleteMQUser 删除mq用户（逻辑删除）
func DeleteMQUser(id uint64) error {
	user := MQUser{}
	return DB.Self.Table("users").Delete(&user, id).Error
}

// @GetMQUserInfo 使用 id 获取mq信息
func GetMQUserInfo(id uint64) (*MQUserInfo, error) {
	u := &MQUserInfo{}
	d := DB.Self.Table("users").Select("username, super, state, createdAt, updatedAt").Where("id = ?", id).First(&u)
	return u, d.Error
}

// mq 列表查询
func ListMQUser(username string, offset, limit int) ([]*MQUser, uint64, error) {
	if limit == 0 {
		limit = constvar.DefaultLimit
	}

	users := make([]*MQUser, 0)
	var count uint64

	where := fmt.Sprintf("username like '%%%s%%'", username)
	if err := DB.Self.Table("users").Model(&MQUser{}).Where(where).Count(&count).Error; err != nil {
		return users, count, err
	}

	if err := DB.Self.Table("users").Where(where).Offset(offset).Limit(limit).Order("id desc").Find(&users).Error; err != nil {
		return users, count, err
	}

	return users, count, nil
}

func (u *MQUserChangePw) ValidateUserPw() error {
	validate := validator.New()
	return validate.Struct(u)
}

// 密码加密
func (u *MQUserChangePw) EncryptUserPW() (err error) {
	// 加密 密码
	u.Pw, err = util.PasswordEncode(u.Pw, "", 901)
	return
}

// 编辑
func (u *MQUserChangePw) UpdateMQPW() error {
	return DB.Self.Table("users").Save(u).Error
}
